import { DownloadOutlined, PlusOutlined, RedoOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, message, Drawer, Alert, Space, Divider } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormSelect, ProFormText, ProFormUploadButton } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import {
  getTaskList,
  createTask,
  getConfigList,
  startTask,
  pauseTask,
  unpauseTask,
  stopTask,
  testTask,
  getSmsTemplateList,
  taskChartsDataDownload,
  importPolicy,
} from './service';
import type { ImportDataReq, InitSelDataType, TableListPagination, TaskListItem } from './data';
import type { CreateTaskReq } from './data';
import TaskDrawDetail from './components/TaskDrawDatail';
import { AliOssUploadFile } from '@/services/ant-design-pro/utils';

const handleAdd = async (fields: CreateTaskReq) => {
  const hide = message.loading('正在添加');
  try {
    await createTask({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

const handleImport = async (fields: ImportDataReq) => {
  const hide = message.loading('正在添加');
  try {
    await importPolicy({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

const processMap = {
  created: 'normal',
  prepared: 'normal',
  processing: 'active',
  completed: 'success',
  paused: 'normal',
  stopped: 'exception',
};

const stateEnum = {
  '': {
    text: '全部',
  },
  created: {
    text: '初始化中',
    status: 'Default',
  },
  prepared: {
    text: '待发送',
    status: 'Default',
  },
  processing: {
    text: '进行中',
    status: 'Processing',
  },
  completed: {
    text: '已完成',
    status: 'Success',
  },
  paused: {
    text: '暂停',
    status: 'Default',
  },
  stopped: {
    text: '停止',
    status: 'Error',
  },
};

const TableList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [importModalVisible, handleImportModalVisible] = useState<boolean>(false);
  const [testTaskModalVisible, handleTestTaskModalVisible] = useState<boolean>(false);
  const [taskDetailRefresh, setTaskDetailRefresh] = useState<number>(0);

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [downloadLoading, setdownloadLoading] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TaskListItem>();

  const [testSMSResult, setTestSMSResult] = useState<string>('');
  const TestSmsResultAlert = () => {
    let ele = <></>;
    if (testSMSResult) {
      ele =
        testSMSResult === '成功' ? (
          <Alert message={'短信已发送，请查收'} type="success" />
        ) : (
          <Alert message={testSMSResult} type="error" />
        );
    }
    return <>{ele}</>;
  };

  const handleDownload = async () => {
    const hide = message.loading('正在导出');
    setdownloadLoading(true);
    try {
      const d = await taskChartsDataDownload();
      hide();
      console.log('u=', d.data.url);
      setdownloadLoading(false);
      window.location.href = d.data.url;
      return true;
    } catch (error) {
      hide();
      setdownloadLoading(false);
      return false;
    }
  };

  useEffect(() => {}, []);

  const columns: ProColumns<TaskListItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'text',
      width: 48,
      search: false,
    },
    {
      title: '标题',
      dataIndex: 'title',
      tip: '任务的标题',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'state',
      valueType: 'text',
      initialValue: '',
      valueEnum: stateEnum,
    },
    {
      title: '总量',
      tip: '导入成功的手机号总量',
      dataIndex: 'count',
      valueType: 'text',
      search: false,
    },
    {
      title: '企微客服配置码',
      dataIndex: 'config_id',
      valueType: 'text',
      copyable: true,
      ellipsis: true,
      search: false,
    },
    {
      title: '进度',
      dataIndex: 'progress',
      valueType: (item) => ({
        type: 'progress',
        status: processMap[item.state],
      }),
      search: false,
    },
    {
      title: '短信模板',
      dataIndex: 'template_content',
      valueType: 'text',
      search: false,
      copyable: true,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '完成时间',
      dataIndex: 'updated_at',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      copyable: true,
      ellipsis: true,
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        record.state == 'prepared' && (
          <a
            key="taskStart"
            onClick={async () => {
              if (!confirm('确认启动')) {
                return false;
              }
              const hide = message.loading('正在启动');
              try {
                await startTask(record.id);
                hide();
                message.success('启动成功');

                if (actionRef.current) {
                  actionRef.current.reload();
                }

                return true;
              } catch (error) {
                hide();
                return false;
              }
            }}
          >
            启动
          </a>
        ),
        record.state == 'prepared' && (
          <a
            key="taskTest"
            onClick={() => {
              setCurrentRow(record);
              handleTestTaskModalVisible(true);
            }}
          >
            测试
          </a>
        ),
        record.state == 'paused' && (
          <a
            key="taskUnpause"
            onClick={async () => {
              const hide = message.loading('正在启动');
              try {
                await unpauseTask(record.id);
                hide();
                message.success('启动成功');

                if (actionRef.current) {
                  actionRef.current.reload();
                }

                return true;
              } catch (error) {
                hide();
                return false;
              }
            }}
          >
            继续
          </a>
        ),
        record.state == 'processing' && (
          <a
            key="taskPause"
            onClick={async () => {
              const hide = message.loading('正在暂停');
              try {
                await pauseTask(record.id);
                hide();
                message.success('暂停成功');

                if (actionRef.current) {
                  actionRef.current.reload();
                }

                return true;
              } catch (error) {
                hide();
                return false;
              }
            }}
          >
            暂停
          </a>
        ),
        (record.state == 'paused' || record.state == 'perpared') && (
          <a
            key="taskStop"
            onClick={async () => {
              if (!confirm('确认停止')) {
                return false;
              }
              const hide = message.loading('正在停止');
              try {
                await stopTask(record.id);
                hide();
                message.success('停止成功');

                if (actionRef.current) {
                  actionRef.current.reload();
                }

                return true;
              } catch (error) {
                hide();
                return false;
              }
            }}
          >
            停止
          </a>
        ),
        <a
          key="taskDetail"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          详情
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      {/* 主表格 */}
      <ProTable<TaskListItem, TableListPagination>
        actionRef={actionRef}
        rowKey="id"
        search={{ labelWidth: 'auto' }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建任务
          </Button>,
          <Button
            type="link"
            key="primary"
            onClick={() => {
              handleImportModalVisible(true);
            }}
          >
            <UploadOutlined /> 导入保单
          </Button>,
          <Button
            type="link"
            key="success"
            loading={downloadLoading}
            onClick={() => {
              handleDownload();
            }}
          >
            <DownloadOutlined /> 导出数据
          </Button>,
        ]}
        request={(params) => getTaskList(params)}
        columns={columns}
        pagination={{
          pageSize: 15,
        }}
      />

      {/* 新建任务模态窗 */}
      <ModalForm
        title="新建任务"
        width="650px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async ({ title, config_id, fileSource, template_id, remark }) => {
          const requestData: CreateTaskReq = {
            title,
            config_id,
            source: fileSource[0].response.name,
            template_id,
            remark,
          };
          // 文件上传path为 value.
          // const fileUploadPath = value?.source[0]?.response?.name
          const success = await handleAdd(requestData);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        initialValues={{}}
        modalProps={{ destroyOnClose: true }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '标题不能为空',
            },
          ]}
          width="xl"
          name="title"
          fieldProps={{ maxLength: 50, showCount: true }}
          label="标题"
        />
        <ProFormSelect
          width="xl"
          name="config_id"
          label="企微客服配置码"
          defaultValue="def"
          rules={[{ required: true, message: '请选择一个客服' }]}
          request={async () => {
            const result = await getConfigList({ pageSize: 10000 }, [], CORP_ID);
            const obj: InitSelDataType[] = [];
            result.data.forEach((item) => {
              obj.push({
                label: item.name + '-' + item.config_id,
                value: item.config_id,
              });
            });
            return obj;
          }}
        />
        <ProFormSelect
          width="xl"
          name="template_id"
          label="短信模板"
          rules={[{ required: true, message: '请选择一个模板' }]}
          request={async () => {
            const result = await getSmsTemplateList({ pageSize: 10000 }, []);
            const obj: InitSelDataType[] = [];
            result.data.forEach((item) => {
              obj.push({
                label: item.name + '-' + item.template_id,
                value: item.template_id,
              });
            });
            return obj;
          }}
        />
        <ProFormUploadButton
          name="fileSource"
          label="数据文件"
          max={1}
          accept="text/csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          fieldProps={{
            name: 'fileSource',
            customRequest: AliOssUploadFile,
          }}
          rules={[
            {
              required: true,
              message: '请上传数据文件',
            },
          ]}
          extra="只允许(xlsx,csv)类型文件，最多上传一个文件"
        />
        <ProFormText width="xl" name="remark" fieldProps={{ maxLength: 50 }} label="备注" />
      </ModalForm>

      {/* 导入保单 */}
      <ModalForm
        title="导入保单"
        width="650px"
        visible={importModalVisible}
        onVisibleChange={handleImportModalVisible}
        onFinish={async ({ fileSource }) => {
          const requestData: ImportDataReq = {
            source: fileSource[0].response.name,
          };
          // 文件上传path为 value.
          // const fileUploadPath = value?.source[0]?.response?.name
          const success = await handleImport(requestData);
          if (success) {
            handleImportModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        initialValues={{}}
        modalProps={{ destroyOnClose: true }}
      >
        <ProFormUploadButton
          name="fileSource"
          label="数据文件（可以多次上传同一份数据，系统内根据保单号去重）"
          max={1}
          accept="text/csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          fieldProps={{
            name: 'fileSource',
            customRequest: AliOssUploadFile,
          }}
          rules={[
            {
              required: true,
              message: '请上传数据文件',
            },
          ]}
          extra="只允许(xlsx,csv)类型文件，最多上传一个文件"
        />
      </ModalForm>

      {/* 任务测试窗口 */}
      <ModalForm
        title="测试任务"
        width="400px"
        visible={testTaskModalVisible}
        onVisibleChange={(v) => {
          // console.log(v);
          setTestSMSResult('');
          handleTestTaskModalVisible(v);
        }}
        onFinish={async (value) => {
          if (!currentRow?.id) {
            return;
          }
          const idStr = currentRow.id;
          const res = await testTask(idStr, { ...value });
          setTestSMSResult(res.data.sms_result);
        }}
        initialValues={{}}
        modalProps={{ destroyOnClose: true }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '手机不能为空',
            },
          ]}
          name="phone"
          fieldProps={{ maxLength: 11, showCount: true }}
          label="接收手机"
        />
        <TestSmsResultAlert />
      </ModalForm>

      {/* 任务详情窗口 */}
      <Drawer
        width={1000}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={true}
        destroyOnClose
        extra={
          <Space>
            <Button
              onClick={() => {
                console.log('aha');
                setTaskDetailRefresh(Math.random());
              }}
              type="primary"
              icon={<RedoOutlined />}
            >
              刷新
            </Button>
          </Space>
        }
      >
        {currentRow?.title && (
          <ProDescriptions<TaskListItem>
            column={2}
            // title={currentRow?.title}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.title,
            }}
            columns={
              columns.filter((item) => {
                return (
                  item.dataIndex != 'option' &&
                  item.dataIndex != 'progress' &&
                  item.dataIndex != 'template_content' &&
                  item.dataIndex != 'id'
                );
              }) as ProDescriptionsItemProps<TaskListItem>[]
            }
          />
        )}
        <Divider />
        {currentRow && <TaskDrawDetail taskId={currentRow.id} refresh={taskDetailRefresh} />}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
